package org.opens.netty.udp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.opens.netty.udp.codec.LogEventDecode;
import org.opens.netty.udp.handle.LogEventHandle;

import java.net.InetSocketAddress;

public class LogEventClient extends Thread {

    private final EventLoopGroup group;

    private final Bootstrap bootstrap;

    private Channel channel;

    public LogEventClient(InetSocketAddress address) {
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new LogEventDecode());
                        ch.pipeline().addLast(new LogEventHandle());
                    }
                })
                .localAddress(address);
    }

    @Override
    public void run() {
        try {
            this.channel = this.bootstrap.bind().syncUninterruptibly().channel();
            this.channel.closeFuture().sync();
        } catch (InterruptedException e) {
            // pass
        }
    }

    public void stopClient() {
        group.shutdownGracefully();
    }

}
